package com.ahaoyou.config;

import com.ahaoyou.datasource.DynamicRoutingDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


@Configuration
public class DataSourceConfigurer {
    @Bean("fluent")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid.fluent")
    public DataSource fluentDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("tsdb")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid.tsdb")
    public DataSource tsdbDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("dynamicDataSource")
    public DataSource dynamicDataSource() {
        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
        Map<Object, Object> dataSourceMap = new HashMap<>(4);
        dataSourceMap.put("fluent", fluentDataSource());
        dataSourceMap.put("tsdb", tsdbDataSource());
        // 设置默认的数据源
        dynamicRoutingDataSource.setDefaultTargetDataSource(tsdbDataSource());
        // 将所有数据源存进map中
        dynamicRoutingDataSource.setTargetDataSources(dataSourceMap);
        return dynamicRoutingDataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //设置实体类包扫描
        bean.setTypeAliasesPackage("com.example.entity");
        //添加SqlSessionFactory的配置
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        //忽略大小写
        configuration.setMapUnderscoreToCamelCase(true);
        //设置属性自动填充
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
        //设置日志
        configuration.setLogImpl(StdOutImpl.class);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }

}
